import Decimal from 'decimal.js';
import dayjs from 'dayjs';
import { customAlphabet } from 'nanoid';

/**
 * 保留两位小数
 * @returns number
 */
export function KeepTwoDecimalPlaces(number: number): number {
    return Number(new Decimal(number).toFixed(2));
}

/**
 * 时间格式化
 * @param date string | Date | number
 * @param format string
 * @returns string
 */
export function formatTimeZone(date: string | Date | number, format: string) {
    return dayjs(date).format(format);
}

/**
 * 生成objectId类
 */
export class creatObjectId {
    private _id: string;

    constructor() {
        this._id = this.generateId();
    }

    // 生成12字节的唯一标识符
    private generateId(): string {
        const timestamp = ((Date.now() / 1000) | 0).toString(16);
        const machineIdentifier = Math.floor(Math.random() * 0xffffff).toString(16);
        const processIdentifier = (Math.random() * 0xffff).toString(16);
        const counter = (Math.random() * 0xffffff).toString(16);

        return [timestamp.padStart(8, '0'), machineIdentifier.padStart(6, '0'), processIdentifier.padStart(4, '0'), counter.padStart(6, '0')].join(
            ''
        );
    }

    // 获取生成的ObjectId
    get id(): string {
        return this._id;
    }

    // 将ObjectId转换为字符串
    toString(): string {
        return this._id;
    }
}

/**
 * 生成随机单号类
 */
export class creatRandomNo {
    private _id: string;

    constructor() {
        const nanoid = customAlphabet('1234567890abcdefghjkmnpqrstuvwxyz', 8);
        this._id = dayjs().format('YYYYMMDD') + '_' + nanoid();
    }

    // 获取生成的ObjectId
    get id(): string {
        return this._id;
    }

    // 将ObjectId转换为字符串
    toString(): string {
        return this._id;
    }
}

/**
 * 字节转mb
 */
export function bytesToMB(bytes: number, precision: number = 2): number {
    const mb = bytes / (1024 * 1024);
    return Number(mb.toFixed(precision));
}
